Page({

  /**
   * 页面的初始数据
   */
  data: {
    taskId: '',
    task: null,
    isLoading: true,
    userInfo: null,
    // 整改反馈表单数据
    feedbackComment: '',
    feedbackImages: [],
    maxImageCount: 4,
    isSubmitting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options && options.id) {
      this.setData({
        taskId: options.id
      });
      
      // 获取用户信息
      const userData = wx.getStorageSync('userData');
      if (!userData) {
        wx.redirectTo({
          url: '/pages/login/login'
        });
        return;
      }
      
      this.setData({
        userInfo: {
          ...userData,
          role: wx.getStorageSync('userRole')  // 确保包含角色信息
        }
      });
      
      // 获取任务详情
      this.fetchTaskDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  /**
   * 获取任务详情
   */
  fetchTaskDetail: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    const db = wx.cloud.database();
    db.collection('tasks')
      .doc(this.data.taskId)
      .get()
      .then(res => {
        if (res.data) {
          // 格式化日期
          const task = {
            ...res.data,
            deadline: this.formatDate(res.data.deadline),
            createTime: this.formatDate(res.data.createTime),
            submitTime: res.data.submitTime ? this.formatDate(res.data.submitTime) : null
          };
          
          this.setData({
            task: task,
            isLoading: false
          });
          
          wx.hideLoading();
        } else {
          this.showError('未找到该任务');
        }
      })
      .catch(err => {
        console.error('获取任务详情失败', err);
        this.showError('获取任务详情失败');
      });
  },
  
  /**
   * 显示错误信息
   */
  showError: function(message) {
    wx.hideLoading();
    wx.showToast({
      title: message,
      icon: 'none'
    });
    
    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  },

  /**
   * 格式化日期
   */
  formatDate: function(date) {
    if (!date) return '';
    
    const d = new Date(date);
    const year = d.getFullYear();
    const month = this.padZero(d.getMonth() + 1);
    const day = this.padZero(d.getDate());
    
    return `${year}-${month}-${day}`;
  },

  /**
   * 数字补零
   */
  padZero: function(num) {
    return num < 10 ? '0' + num : num;
  },
  
  /**
   * 输入反馈内容
   */
  onFeedbackInput: function(e) {
    this.setData({
      feedbackComment: e.detail.value
    });
  },
  
  /**
   * 上传图片
   */
  chooseImage: function() {
    const remainCount = this.data.maxImageCount - this.data.feedbackImages.length;
    
    if (remainCount <= 0) {
      wx.showToast({
        title: `最多上传${this.data.maxImageCount}张图片`,
        icon: 'none'
      });
      return;
    }
    
    wx.chooseImage({
      count: remainCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        // 添加到本地显示
        this.setData({
          feedbackImages: [...this.data.feedbackImages, ...res.tempFilePaths]
        });
      }
    });
  },
  
  /**
   * 删除图片
   */
  deleteImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.feedbackImages];
    images.splice(index, 1);
    
    this.setData({
      feedbackImages: images
    });
  },
  
  /**
   * 预览图片
   */
  previewImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const source = e.currentTarget.dataset.source;
    let images = [];
    
    if (source === 'feedback') {
      images = this.data.feedbackImages;
    } else if (source === 'task') {
      images = this.data.task.images || [];
    } else if (source === 'submit') {
      images = this.data.task.submitImages || [];
    }
    
    if (images && images.length > 0) {
      wx.previewImage({
        current: images[index],
        urls: images
      });
    }
  },
  
  /**
   * 提交整改反馈
   */
  submitFeedback: async function() {

// 校验用户是否为本宿舍成员
if (
  this.data.userInfo.role !== '学生' ||
  !this.data.task ||
  this.data.userInfo.building !== this.data.task.building ||
  this.data.userInfo.roomNo !== this.data.task.roomNo
) {
  wx.showToast({
    title: '你无权提交该宿舍的整改',
    icon: 'none'
  });
  return;
}

    // 验证表单
    if (!this.data.feedbackComment.trim()) {
      wx.showToast({
        title: '请输入整改内容',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ isSubmitting: true });
    
    try {
      // 1. 上传图片到云存储
      const uploadPromises = this.data.feedbackImages.map(filePath => this.uploadFile(filePath));
      const fileIDs = await Promise.all(uploadPromises);
      
      // 获取当前用户信息
      const currentUserData = {
        openid: this.data.userInfo.openid,
        building: this.data.userInfo.building,
        roomNo: this.data.userInfo.roomNo,
        role: this.data.userInfo.role
      };

      console.log('提交整改的用户数据：', currentUserData);

      // 2. 更新任务状态
      const submitResult = await wx.cloud.callFunction({
        name: 'submitTaskFeedback',
        data: {
          taskId: this.data.taskId,
          comment: this.data.feedbackComment,
          images: fileIDs,
          userData: currentUserData  // 传递完整的用户数据
        }
      });

      if (!(submitResult.result && submitResult.result.success)) {
        throw new Error(submitResult.result.error || '云函数submitTaskFeedback返回失败');
      }
      
      // 3. 显示成功提示
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      });
      
      // 4. 重新获取任务详情
      setTimeout(() => {
        this.fetchTaskDetail();
        this.setData({
          feedbackComment: '',
          feedbackImages: [],
          isSubmitting: false
        });
      }, 1500);
      
    } catch (err) {
      console.error('提交整改反馈失败', err);
      wx.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      });
      this.setData({ isSubmitting: false });
    }
  },
  
  /**
   * 上传单个文件到云存储
   */
  uploadFile: function(filePath) {
    const cloudPath = `tasks/feedback/${this.data.taskId}/${Date.now()}-${Math.random().toString(36).substr(2)}.${filePath.match(/\.([^.]+)$/)[1]}`;
    
    return wx.cloud.uploadFile({
      cloudPath,
      filePath
    }).then(res => res.fileID);
  },
  
  /**
   * 完成整改任务（宿管操作）
   */
  completeTask: function() {
    wx.showModal({
      title: '完成整改任务',
      content: '确认该宿舍已完成整改任务吗？',
      success: res => {
        if (res.confirm) {
          this.setData({ isSubmitting: true });
          
          wx.cloud.callFunction({
            name: 'completeTask',
            data: {
              taskId: this.data.taskId
            }
          }).then(res => {
            if (res.result && res.result.success) {
              // 刷新任务详情以获取最新状态
              this.fetchTaskDetail();
              
              wx.showToast({
                title: '操作成功',
                icon: 'success'
              });
              
              // 延迟返回，确保用户看到成功提示和更新后的状态
              setTimeout(() => {
                // 返回上一页并刷新
                const pages = getCurrentPages();
                const prevPage = pages[pages.length - 2];
                if (prevPage && prevPage.fetchTasks) {
                  prevPage.fetchTasks();
                }
                wx.navigateBack({
                  delta: 1
                });
              }, 1500);
            } else {
              // 显示云函数返回的错误信息
              wx.showToast({
                title: res.result.error || '操作失败',
                icon: 'none'
              });
              this.setData({ isSubmitting: false });
            }
          }).catch(err => {
            console.error('完成整改任务失败', err);
            wx.showToast({
              title: '操作失败，请重试',
              icon: 'none'
            });
            this.setData({ isSubmitting: false });
          });
        }
      }
    });
  }
}) 